package com.endlessblue.visa.util;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Component;


/**
 * String session缓存工具类
 * @author sonta
 *
 */
@Component
public class SessionCacheUtil {
	
	private static Cache cache;
	
	public static String SESSION_FLAG = "appSid";
	
	public static String getSessionId (HttpServletRequest request) {
		return request.getParameter(SESSION_FLAG);
	}
	
	/**
	 * 获取session
	 * @param cacheKey
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> getSessionMap(HttpServletRequest request) {
		String sid = request.getParameter(SESSION_FLAG);
		if (sid == null) {
			return null;
		}
		if (cache.get(sid) == null) {
			return null;
		}
		return (Map<String, Object>) cache.get(sid).get();
	}  
	
	public static void setSessionMap(HttpServletRequest request, Map<String, Object> prams) {
		String sid = request.getParameter(SESSION_FLAG);
		if (sid == null) {
			return;
		}
		if (cache.get(sid) == null) {
			return;
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> sessionMap = (Map<String, Object>) cache.get(sid).get();
		sessionMap.putAll(prams);
	}
	
	public static void setSessionMap(HttpServletRequest request, String name, Object value) {
		String sid = request.getParameter(SESSION_FLAG);
		if (sid == null) {
			return;
		}
		if (cache.get(sid) == null) {
			return;
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> sessionMap = (Map<String, Object>) cache.get(sid).get();
		sessionMap.put(name, value);
	}
	
	/**
	 * 获取session
	 * @param cacheKey
	 * @return
	 */
	public static Object getCache(String cacheKey) {  
	    return cache.get(cacheKey);
	}  
	/* 
	 * 将对象添加到缓存中 
	 */  
	public static void setCache(String cacheKey, Object result){  
		cache.put(cacheKey, result);
	}
	
	/**
	 * 清除指定缓存
	 * @param appSid
	 */
	public static void evictSession (HttpServletRequest request) {
		String sid = request.getParameter(SESSION_FLAG);
		if (sid == null) {
			return;
		}
		cache.evict(sid);
	}
	
	/**
	 * 强制下线
	 * @param appSid
	 */
	public static void kickOut(String appSid) {
		if (cache.get(appSid) == null) {
			return;
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> sessionMap = (Map<String, Object>) cache.get(appSid).get();
		sessionMap.put("isKickOut", true); // 设置被踢状态，下次访问则会自动下线
	}
	
	@Resource
	public void setCacheManager(EhCacheCacheManager cacheManager) {
		SessionCacheUtil.cache = cacheManager.getCache("sessionCache");
	}
	
}
